package leetCode.secondWeek;

import java.util.LinkedList;
import java.util.List;

public class Code_54 {
  public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> res = new LinkedList<>();
    if (matrix.length == 0) {
      return res;
    }
    int[][] matrixTmp = matrix;
    int directionX = 0, directionY = 1;
    int posX = 0, posY = 0;
    for (int i = 0; i < matrix.length * matrix[0].length; i++) {
      res.add(matrixTmp[posX][posY]);
      matrixTmp[posX][posY] = 0;

      int returnX = retdirection(posX, posY, directionX, directionY, matrix)[0];
      int returnY = retdirection(posX, posY, directionX, directionY, matrix)[1];

      if (returnX != 0 | returnY != 0) {
        directionX = returnX;
        directionY = returnY;
        posX += directionX;
        posY += directionY;
        continue;
      }

      posX += directionX;
      posY += directionY;
    }

    return res;
  }

  public int[] retdirection(int posX, int posY, int directionX, int directionY, int[][] matrix) {
    if (posY + directionY == matrix[0].length
        | posX + directionX == matrix.length
        | posY + directionY == -1) {
      if (directionX != 0) {
        return new int[] {0, -directionX};
      } else if (directionY != 0) {
        return new int[] {directionY, 0};
      }
    }
    if (matrix[posX + directionX][posY + directionY] == 0) {
      if (directionX != 0) {
        return new int[] {0, -directionX};
      } else if (directionY != 0) {
        return new int[] {directionY, 0};
      }
    }
    return new int[] {0, 0};
  }
}
